// pages/mail/mail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    citys: [],
    index: -1,
    isShowGoods: false,
    goodsTypeLists: [],
    lock: false,
    fileList: [],                       // 照片列表
    goodsName: "",                      // 包裹类型
    goodsWeight: 1,                     // 包裹重量
    goodsInfoText: "",                  // 货物信息描述文本（用于选择完包裹类型、重量后展示）
    post_communicate_id: 0,             //寄件人ID
    senderName: "",                     // 寄件人姓名
    senderPhone: "",                    // 寄件人电话
    senderAddress: "",
    card_img_pros: "",                  // 寄件人地址
    receive_communicate_id: 0,          //收件人ID
    addresseeName: "",                  // 收件人姓名
    addresseePhone: "",                 // 收件人电话
    addresseeAddress: "",               // 收件人地址
    startCity: "",                      // 始发城市
    endCity: "",                        // 送达城市
    freight: 0,                 //运费预估
    employee_id: 0,                    //揽件员ID，这里先暂时写死
    tansline_id: 0,           //当前选择的线路ID
    rate: 0,                   //当前线路的运费单价
    post_lng: '',             //寄件点纬度
    post_lat: '',           //寄件端纬度
    isUpload: false,
  },

  /**
   * 跳转到通讯录
   */
  toContact: function (e) {
    let source = 'mail';
    let type = e.currentTarget.dataset.type;
    console.log(e)
    wx.navigateTo({
      url: '/pages/contact/contact?source=' + source + "&type=" + type,
    })
  },
  uploadImage(e) {
    let that = this;
    wx.chooseImage({
      complete: (res) => {
        that.commonUpImage(res.tempFilePaths[0], e.currentTarget.dataset.type);
      },
    })
  },

  /**
   * 上传图片
   */
  commonUpImage: function (file_path, type) {
    console.log(file_path)
    let that = this;
    wx.uploadFile({
      url: wx.$config.serverAddress + 'employee/scanWayBillPaper',
      filePath: file_path,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: { 'file': file_path, 'token': wx.getStorageSync('token') },
      success(res) {
        let get_data = JSON.parse(res.data);
        console.log(get_data)
        that.setData({
          senderName: get_data.data.SendName,
          senderPhone: get_data.data.SendTel,
          senderAddress: get_data.data.SendAddr,
          addresseeName: get_data.data.RecName,
          addresseePhone: get_data.data.RecTel,
          addresseeAddress: get_data.data.RecAddr,
          card_img_pros: get_data.data.url
        })

      }
    });
  },
  /**
   * 修改通讯录信息
   * @param {*} options 
   */
  changeSenderInfo: function (options) {
    let data = {};
    console.log('get_sender', options);
    if (options.type == 'addressee') {      //收件员ID
      data.receive_communicate_id = options.communicate_id;
    } else {      //寄件员ID
      data.post_communicate_id = options.communicate_id;
    }
    if (options.type == undefined) {
      data.senderName = options.name;
      data.senderPhone = options.phone;
      data.senderAddress = options.address;
    } else {
      data[options.type + 'Name'] = options.name;
      data[options.type + 'Phone'] = options.phone;
      data[options.type + 'Address'] = options.address;
    }

    this.setData(data);
  },

  /**
   * 选择城市
   * @param {}} e 
   */
  changeCity: function (e) {
    console.log('change_city', e);
    this.setData({
      tansline_id: this.data.citys[e.detail.value].tansline_id,
      rate: this.data.citys[e.detail.value].rate,
      endCity: this.data.citys[e.detail.value].tansline_end_district,
      freight: parseInt(this.data.citys[e.detail.value].rate) * parseInt(this.data.goodsWeight)
    });
  },

  /**
   * 展示货物信息选择弹框
   */
  showGoodsPopup: function () {
    this.setData({
      isShowGoods: true
    })
  },

  /**
   * 关闭货物信息选择弹框
   */
  closeGoodsPopup: function () {
    this.setData({
      isShowGoods: false
    })
  },

  /**
   * 选择货物类型
   */
  changeGoodsType: function (e) {
    let index = e.currentTarget.dataset.index;
    console.log('change_goods', index);
    let goodsName = "";
    if (index == undefined) {
      goodsName = e.detail;
    } else {
      goodsName = this.data.goodsTypeLists[index].name;
    }
    this.setData({
      goodsTypeLists: this.data.goodsTypeLists.map((item, i) => {
        if (index === i) {
          item.isActive = true;
        } else {
          item.isActive = false;
        }
        return item;
      }),
      goodsName: goodsName
    })
    console.log(goodsName)
  },

  /**
   * 选择货物重量
   * @param {*} e 
   */
  changeGoodsWeight: function (e) {
    console.log(e)
    this.setData({
      goodsWeight: e.detail
    })
  },

  /**
   * 修改收寄件人信息
   * @param {*} e 
   */
  changePerson(e) {
    let { type } = e.currentTarget.dataset;
    let data = {};
    data[type] = e.detail;
    this.setData(data)
    console.log(e, ":::::::::::::::changePerson", data)
  },

  /**
   * 提交货物信息
   */
  submitGoodsInfo: function () {
    if (!this.data.goodsName) {
      return wx.$Toast('请选择货物类型');
    }

    if (!this.data.goodsWeight) {
      return wx.$Toast('请选择货物重量');
    }
    this.setData({
      isShowGoods: false,
      freight: parseInt(this.data.goodsWeight) * parseInt(this.data.rate),
      goodsInfoText: this.data.goodsName + "  " + this.data.goodsWeight + "KG"
    })
  },

  beforeRead(event) {
    const { file, callback } = event.detail;
    callback(file.type === 'image');
  },

  afterRead(event) {
    if (this.data.isUpload) {
      return;
    }
    this.setData({
      isUpload: true
    })
    console.log(22222)
    let that = this;
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    console.log('file', file);
    setTimeout(() => {
      wx.uploadFile({
        url: wx.$config.serverAddress + 'upimg', // 仅为示例，非真实的接口地址
        filePath: file.path,
        name: 'file',
        formData: { 'file': file.path },
        success(res) {
          let get_data = JSON.parse(res.data);
          if (get_data.code != 200) {
            wx.$Toast(get_data.msg);
            return;
          }
          // 上传完成需要更新 fileList
          console.log('suceess', get_data);
          const fileList = that.data.fileList;
          fileList.push({ ...file, url: get_data.data.url });
          console.log('fileList', fileList);
          that.setData({ fileList });
          that.setData({
            isUpload: false
          })
        }
      });
    }, 5000)



  },

  /**
   * 提交货物信息
   */
  submitMail: function () {
    if (!this.data.senderName) {
      return wx.$Toast('请输入寄件人姓名');
    }
    if (!this.data.senderPhone) {
      return wx.$Toast('请输入寄件人联系方式');
    }
    if (!this.data.senderAddress) {
      return wx.$Toast('请输入寄件人地址');
    }
    if (!this.data.addresseeName) {
      return wx.$Toast('请输入收件人姓名');
    }
    if (!this.data.addresseePhone) {
      return wx.$Toast('请输入收件人联系方式');
    }
    if (!this.data.addresseeAddress) {
      return wx.$Toast('请输入收件人地址');
    }
    // if(!this.data.endCity){
    //   return wx.$Toast('请选择送达城市');
    // }
    if (!this.data.goodsName || !this.data.goodsWeight) {
      return wx.$Toast('请选择货物信息');
    }

    // if(!this.data.fileList.length){
    //   return wx.$Toast('请上传照片');
    // }
    let pictures_urls = [];
    for (let val of this.data.fileList) {
      pictures_urls.push(val.url);
    }
    let post_data = {
      employee_id: this.data.employee_id,
      // trans_line_id: this.data.tansline_id,
      post_communicate_id: this.data.post_communicate_id,
      post_communicate_name: this.data.senderName,
      post_communicate_mobile: this.data.senderPhone,
      post_communicate_address: this.data.senderAddress,
      receive_communicate_id: this.data.receive_communicate_id,
      receive_communicate_name: this.data.addresseeName,
      receive_communicate_mobile: this.data.addresseePhone,
      receive_communicate_address: this.data.addresseeAddress,
      // pictures_urls: pictures_urls,
      goods_type: this.data.goodsName,
      // post_lng: this.data.post_lng,
      // post_lat: this.data.post_lat,
      expected_money: this.data.freight,
      weight: this.data.goodsWeight
    };
    let { lock } = this.data;
    if (!lock) {
      this.setData({ lock: true });
      //数据请求操作
      wx.$api.submitMail(post_data).then(res => {
        console.log(res);
        if (res.data.code != 200) {
          wx.$Toast(res.data.msg);
          return;
        } else {
          this.setData({ lock: false });
        }
        wx.$Toast(res.data.msg);
        wx.navigateTo({
          url: '/pages/index/index',
        })
      })
      //请求完成后 开锁

    }

  },
  async getEmployeeId() {
    wx.$api.getEmployeeId().then(res => {
      console.log(res);
      if (res.data.code == 200) {
        this.setData({ employee_id: res.data.data.employee_id });
        this.getCompanyDetail();
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initIndex(options)
  },

  async initIndex(options) {
    if (!wx.getStorageSync('is_certification')) {    //如果没有实名认证的话，这里跳转到实名认证
      wx.navigateTo({
        url: '/pages/verified/verified',
      })
    }
    if (options.scene == undefined) {
      // wx.navigateTo({
      //   url: '/pages/index/index',
      // })
      await this.getEmployeeId();
    } else {
      let options_employee_id = options.scene || 0;
      this.setData({ employee_id: options_employee_id });
      this.getCompanyDetail();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 获取企业相关详情
   */
  getCompanyDetail: function () {
    wx.$api.getCompanyDetail({ employee_id: this.data.employee_id }).then(res => {
      if (res.data.code != 200) return wx.$Toast(res.data.msg);
      this.setData({
        goodsTypeLists: res.data.data.good_type,
        citys: res.data.data.tanslines,
        post_communicate_id: res.data.post_communicate ? res.data.post_communicate.post_communicate_id : 0,
        senderName: res.data.post_communicate ? res.data.post_communicate.senderName : '',
        senderPhone: res.data.post_communicate ? res.data.post_communicate.senderPhone : ''
      });

    });

  }
})